<%@page import="java.net.URLDecoder"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.io.*" %>
<%@ page import="org.apache.poi.poifs.filesystem.POIFSFileSystem" %>
<%@ page import="org.apache.poi.poifs.filesystem.DocumentEntry" %>
<%@ page import="org.apache.poi.poifs.filesystem.DirectoryEntry" %>
<%@ page import="com.micro.model.Subject" %>
<%@ page import="com.micro.service.SubjectService" %>
<%@ page import="org.springframework.context.ApplicationContext" %>
<%@ page import="org.springframework.context.support.ClassPathXmlApplicationContext" %>
<%@ page import="com.micro.util.EncodeURIUtil" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>word导出</title>
</head>
    <%
	response.setCharacterEncoding("UTF-8");
	request.setCharacterEncoding("UTF-8");

    String subjectId = (String)request.getParameter("doc");//直接传递

	if (subjectId != null) {
        Subject subject = new Subject();
        subject.setSubjectId(subjectId);

        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:conf/spring.xml"
                ,"classpath:conf/spring-mybatis.xml"});
        SubjectService subjectService = (SubjectService) context.getBean("subjectServiceImpl");
        Subject subjectResult = subjectService.querySubjectListByID(subject);

		OutputStream outStream = null;
		FileInputStream fileInputStream = null;

        String contentConcat = "<html>" +
                "<meta charset='UTF-8'>"+
                "<body>" + subjectResult.getSubjectContent() + "</body>" +
                "</html>";

        byte b[] = contentConcat.getBytes("UTF-8");
        ByteArrayInputStream bais = new ByteArrayInputStream(b);

        POIFSFileSystem poifs = new POIFSFileSystem();

        DirectoryEntry directory = poifs.getRoot();

        DocumentEntry documentEntry = directory.createDocument("WordDocument", bais); //该步骤不可省略，否则会出现乱码。

        //输出文件
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/msword");//导出word格式

        String fileName = subjectResult.getSubjectTitle() + ".doc";
//        byte[] bt = fileName.getBytes("UTF-8");
//        String unicoStr = new String(bt, "UTF-8");

        String headerValue = "attachment;";
        headerValue += " filename=\"" + EncodeURIUtil.encodeURIComponent(fileName) + "\";";
        headerValue += " filename*=utf-8''" + EncodeURIUtil.encodeURIComponent(fileName);
        response.setHeader("Content-Disposition", headerValue);

//        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        ServletOutputStream ostream = response.getOutputStream();
        poifs.writeFilesystem(ostream);
        bais.close();
        ostream.close();
	}
%>